<?php

namespace app\api\controller\customer;

use app\api\controller\Api;
use app\common\customer\model\Customer;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerBanquet;
use app\common\customer\validate\CustomerProductValidate;
use think\db\exception\DbException;

class Product extends Api
{
    public function read()
    {
        $post = $this->request->post();

        // 获取意向产品
        $productModel = new CustomerBanquet();
        $products = $productModel->where('member_id', $post['id'])->select();
        foreach ($products as $row) {
            $row->append(['category', 'creator', 'city', 'tag']);
        }
        $result['products'] = $products;

        return success($result);
    }

    public function save()
    {
        $post = $this->request->post();

        $validate = new CustomerProductValidate();
        if (!$validate->scene('create')->check($post)) {
            return error([], $validate->getError());
        }
        $customerModel = new Customer();
        $customer = $customerModel->where('id', $post['member_id'])->find();

        $productModel = new CustomerBanquet();
        $productModel->startTrans();
        try {
            $row = $productModel->where('id', $post['id'])->find();
            $row->save($post);

            if ($customer['category_id'] != $post['category_id']) {
                $customer->save(['category_id' => $post['category_id']]);
            }
            $productModel->commit();
        } catch (DbException $e) {
            $productModel->rollback();
            return error([], $e->getMessage());
        }

        return success([], "更新成功");
    }

    // 季总
    public function update()
    {
        $memberId = $this->request->param('member_id');
        $allocateId = $this->request->param('allocate_id');
        $user = $this->request->user;
        $allocateModel = new CustomerAllocate();
        $allocate = $allocateModel->where('id', $allocateId)->where('user_id', $user['id'])->find();
        if (empty($allocate)) return error([], "无权限");
        if ($allocate['member_id'] != $memberId) return error([], "客资不匹配");

        $model = new CustomerBanquet();
        $model->startTrans();
        $row = $model->where('member_id', $memberId)->find();
        $post = $this->request->post();
        try {
            $data = [];
            $data['zone'] = $post['zone'];
            $data['event_date'] = $post['event_date'];
            $data['table_amount'] = $post['table_amount'];
            $data['budget'] = $post['budget'];
            $row->save($data);
            $model->commit();
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        
        $model->commit();
        return success([], "更新成功");
    }
}